package com.arobs.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.arobs.model.Exercise;
import com.arobs.service.StatisticsService;

@Controller
@SessionAttributes("statistics")
public class StatisticsController {
	@Autowired
	private StatisticsService statisticsService;

	
	
	@RequestMapping(value = "addNewValue", method = RequestMethod.GET)
	public String prepareSubmitValue(Model model) {
		Exercise exercise = new Exercise();
		model.addAttribute("newValue", exercise);
		
		return "addNewValue";
	}

	@RequestMapping(value = "addNewValue", method = RequestMethod.POST)
	public String updateGoal(@Valid @ModelAttribute("newValue") Exercise exercise, Model model, BindingResult result, HttpServletRequest request) {
		
		int minutes = exercise.getMinutes();
		String activity = exercise.getActivity();
		
		Map<String, Integer> statisticsMap = (Map<String, Integer>) request.getAttribute("statistics");
		
		if (statisticsMap == null) {
			statisticsMap = new HashMap<String, Integer>();
			request.setAttribute("statistics", statisticsMap);
		}
		
		Integer totalMinutes =  statisticsMap.get(activity);
		
		statisticsMap.put(activity, totalMinutes == null ? minutes : totalMinutes  + minutes);
		statisticsService.addNewValue(activity, minutes);
		
		System.out.println("Statistics for current user : " + statisticsMap);
		
		if(result.hasErrors()) {
			return "addGoal";
		}
		
		
		
		return "redirect:addNewValue.html";
	}
	
	@RequestMapping(value = "getStatistics", method = RequestMethod.GET)
	public @ResponseBody Map<String, Map> getStatistics(HttpServletRequest request) {
		Map<String, Map> statisticsMap = new HashMap<String, Map>();
		Map sessionStatistics = (Map) request.getAttribute("statistics");
		Map globalStatistics = statisticsService.getGlobalStatistics();
		
		statisticsMap.put("sessionStatistics", sessionStatistics);
		statisticsMap.put("globalStatistics", globalStatistics);
		
		System.out.println(statisticsMap.toString());
		
		return statisticsMap;
	}

	
}
